package common

import (
	"github.com/dgrijalva/jwt-go"
	"mall-go/model"
	"time"
)

var jwtKey = []byte("a_secret_create")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

// ReleaseAdminToken 生成后台用户token
func ReleaseAdminToken(user model.NewBeeAdminUser) (string, error) {
	expire := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.AdminUserId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expire.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "zhongyang",
			Subject:   "user token",
		},
	}
	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := jwtToken.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// ReleaseMallToken 生成商城用户token
func ReleaseMallToken(user model.MallUser) (string, error) {
	expire := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.UserID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expire.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "zhongyang",
			Subject:   "user token",
		},
	}
	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := jwtToken.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func ParseToken(tokenstring string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenstring, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	return token, claims, err
}
